# -*- coding: utf-8 -*-
import logging
from datetime import datetime, timedelta

from django.views.decorators.http import require_GET, require_POST
from future.utils import raise_with_traceback

from api.scrolling.logic import view_scrolling
from common.campaign import daily_recharge
from common.campaign import moist, daily_bet_return, daily_recharge_return, daily_treasure_return, winner_ranking_award
from common.campaign import wheel
from common.campaign.winner_ranking_award import get_daily_pool, get_weekly_pool, get_total_pool
from common.preset.db.banner import get_banner_by_type
from common.preset.model.preset import BANNER_TYPE
from common.utils import exceptions as err
from common.utils.api import token_required
from common.utils.decorator import response_wrapper
from common.utils.exceptions import ParamError

_LOGGER = logging.getLogger('campaign')

HANDLERS = {
    'moist': moist,
    'daily_recharge': daily_recharge,  # 满 300 送 10，旧活动，目前没有启用
    'daily_bet_return': daily_bet_return,  # 每日流水返现（流水闯关）
    'daily_recharge_return': daily_recharge_return,  # 每日充值返现（元旦充值大狂欢）
    'daily_treasure_return': daily_treasure_return,  # 每日流水得宝箱
    'winner_ranking_award': winner_ranking_award,  # 中奖排行榜
}


@require_GET
@response_wrapper
def view_campaign_status(request, campaign_name):
    campaign_handler = HANDLERS.get(campaign_name)
    if not campaign_handler:
        raise err.ParamError('campaign name invalid')
    user_id = int(request.user_id) if request.user_id else None
    applied = campaign_handler.get_campaign_status(user_id)
    data = {
        'applied': applied
    }
    return data


@require_GET
@response_wrapper
def view_winner_pool(request):
    banner = get_banner_by_type(BANNER_TYPE.WINNER_RANKING)
    campaign_start = datetime.fromtimestamp(banner.campaign_start)
    now = datetime.now()
    delta_time = (now - campaign_start).days / 7 * 7
    weekly_start_date = campaign_start + timedelta(days=delta_time)
    data = {
        'applied': {
            'daily': get_daily_pool(datetime.utcnow()),
            'weekly': get_weekly_pool(weekly_start_date),
            'total': get_total_pool()
        }
    }
    return data


@require_GET
@response_wrapper
@token_required
def award(request, campaign_name):
    campaign_handler = HANDLERS.get(campaign_name)
    if not campaign_handler:
        raise err.ParamError('campaign name invalid')
    campaign_handler.award(request.user_id)
    return {}


@require_GET
@response_wrapper
def scrolling(request, campaign_name):
    if campaign_name not in HANDLERS:
        raise err.ParamError('campaign name invalid')
    scrolling_list = view_scrolling(campaign_name)
    data = {
        'size': len(scrolling_list),
        'list': scrolling_list
    }
    return data


@require_GET
@response_wrapper
def get_wheel_timeline(request):
    """
    获取活动奖励的时间线
    """
    a_list = wheel.get_timeline()
    return {
        'list': a_list
    }


@require_GET
@response_wrapper
@token_required
def get_wheel_award_list(request):
    """
    获取用户中奖列表
    """
    try:
        page = int(request.GET.get('page', 0))
        size = int(request.GET.get('size', 0))
    except Exception as e:
        raise_with_traceback(ParamError(e))

    user_id = request.user_id
    a_list = wheel.get_user_award(user_id, page, size)
    return {
        'list': a_list
    }


@require_GET
@response_wrapper
@token_required
def get_wheel_status(request):
    """
    获取用户的转盘状态
    """
    user_id = request.user_id
    return wheel.get_status(user_id)


@require_POST
@response_wrapper
@token_required
def play_wheel(request):
    """
    摇奖
    """
    user_id = request.user_id
    award_index, is_double = wheel.single_play(user_id)
    return {
        'award_index': award_index,
        'is_double': is_double
    }
